//
//  MainViewController.swift
//  XLWB
//
//  Created by MacBook on 16/6/29.
//  Copyright © 2016年 MacBook. All rights reserved.
//

import UIKit
import SVProgressHUD
class MainViewController: UITabBarController {

    //定时器
    private var time: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()
        
        setupTimer()
        
        setupNewfeatureViews()
        
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }

    deinit {
        time?.invalidate()
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    
    //MARK--通知监听
    @objc private func userLogin(n: Notification) {
    
        print("用户登录通知 \(n)")
        
        //展现登录控制器
//        let nav = UINavigationController(rootViewController: WBOAuthViewController())
//        present(nav, animated: true, completion: nil)
    
        var when = DispatchTime.now()
        
        //判断n.objct是否有值
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            
            SVProgressHUD.showInfo(withStatus: "用户登录超时,请重新登录")
            
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.after(when: when) {
        
            SVProgressHUD.setDefaultMaskType(.clear)
            
            let nav = UINavigationController(rootViewController: WBOAuthViewController())
            
            self.present(nav,animated: true, completion: nil)
        
        
        }
    }
    
    //MARK--撰写按钮监听
   @objc private func composeStatus() {
    
         print("监听")

         //1.实例化视图
         let v = WBComposeTypeView.composeTypeView()
    
          //2.显示视图
    v.show { [weak v] (clsName) in
        print(clsName)
        
        // 展现撰写微博控制器
        guard let clsName = clsName,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type
            else {
                v?.removeFromSuperview()
                return
        }
        
        let vc = cls.init()
        let nav = UINavigationController(rootViewController: vc)
        
        self.present(nav, animated: true) {
            v?.removeFromSuperview()
        }
    }

    
    }
    
   //MARK--返回支持设备的方向,TaBar及子控制器竖屏,Modal展现的控制器会支持横屏
   override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        
        return .portrait
    }
    
   //MARK-撰写按钮
   private lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

}

//MARK--时钟
extension MainViewController {

    private func setupTimer() {
    
    time = Timer.scheduledTimer(timeInterval: 20.0, target: self, selector: #selector(uptime), userInfo: nil, repeats: true)
    
    }


//时钟触发方法
    @objc private func uptime() {
    
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        WBNetworkManager.shared.unreadCount { (count) in
            
            print("检测到\(count) 条新微博")
            
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            //设置app的badgeNumber,ios8.0以后需要用户授权
            UIApplication.shared().applicationIconBadgeNumber = count
        }
    }
}

//MARK--新特性视图处理
extension MainViewController {

    private func setupNewfeatureViews() {
    
        //判断是否登录
        if !WBNetworkManager.shared.userLogon {
        
        
            return
        }
        
        
        
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        
        
        view.addSubview(v)
    }

    /**
     版本号
     - 在 AppStore 每次升级应用程序，版本号都需要增加，不能递减
     
     - 组成 主版本号.次版本号.修订版本号
     - 主版本号：意味着大的修改，使用者也需要做大的适应
     - 次版本号：意味着小的修改，某些函数和方法的使用或者参数有变化
     - 修订版本号：框架／程序内部 bug 的修订，不会对使用者造成任何的影响
     */

    private var isNewVersion: Bool {
    
        //1.取当前版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print("当前版本" + currentVersion)
        //2.取保存在Document目录中之前的版本号
        
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        print("沙盒版本" + sandboxVersion)
        //3.将当前版本号保存在沙盒
        
        _ = try? currentVersion.write(toFile: path,atomically: true, encoding: .utf8)
        //4.返回两个版本号是否一致
        
        
        
        return currentVersion != sandboxVersion
    }
}


//MARK-- UITabBarControllerDelegate

extension MainViewController: UITabBarControllerDelegate {

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        print("将要切换到\(viewController)")
        
//        //判断目标控制器是否是UIViewController
//        return !viewController.isMember(of: UIViewController.self)
        //获取控制器在数组中的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        //2判断当前索引是首页,同事idx也是首页,重复点击首页的按钮
        if selectedIndex == 0 && idx == selectedIndex {
            
            print("点击首页")
            
            //3.让表格滚动到顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            //滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            //刷新数据-增加延迟,保证表格先滚动到顶部在刷新
            DispatchQueue.main.after(when: DispatchTime.now() + 1, execute: { 
                vc.loadData()
            })
            
            //清楚tabItem的badgeNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared().applicationIconBadgeNumber = 0
        }
        // 判断目标控制器是否是 UIViewController
        return !viewController.isMember(of: UIViewController.self)

    }

}

extension MainViewController {

    //设置按钮
    private func setupComposeButton() {
    
        tabBar.addSubview(composeButton)
        
        //计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        
        let w = tabBar.bounds.width / count
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        print("撰写按钮的宽度\(composeButton.bounds.width)")
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    
    
    
    
    }
    
    
    func setupChildControllers() {
    

        
        //获取沙盒路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("demo.json")
        
        //加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        //判断data是否有内容,如果没有,说明本地沙盒没有保存文件
        if data == nil {
            let path = Bundle.main.pathForResource("demo.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        guard let array = try! JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
            else {
                
                return
        }

        
        var arrayM = [UIViewController]()
        for dict in array {
        
            arrayM.append(controller(dict: dict))
        
        }
    
        viewControllers = arrayM
    
    }
    
    
    
    
    //使用字典创建一个子控制器
    private func controller(dict: [String: AnyObject]) -> UIViewController {
    
        guard let clsName = dict["clsName"] as? String,
        title = dict["title"] as? String,
        imageName = dict["imageName"] as? String,
            cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            visitorDict = dict["visitorInfo"] as? [String: String]

            
        else {
            return UIViewController()
        }
    
        //创建视图控制器
        let vc = cls.init()
        vc.title = title
        
        //设置控制器的访客信息字典
        vc.visitorInfoDictionary = visitorDict
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        //设置tabbar的字体大小和颜色
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange()], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue: 0))
        
        let nav = WBNavigationController(rootViewController:vc)
        
        return nav
        
        
    }

}
